const mysql = require('./mysqlPool');
const utils = require('../utils/util')


async function getLatestIndex(){
    let ds = await mysql("SELECT `id` FROM t_ms ORDER BY `id` DESC LIMIT 0,1");
    return ds[0].id;
}



async function getNextData(id){
    let ds = await mysql("SELECT *,DATE_FORMAT(`timestamp`,'%Y-%m-%d %H:%i:%S') AS `ts` FROM t_ms WHERE `id` = "+id);

    if(ds.length == 0 || ds[0].id == (id-1)) return {};

    ds[0].ds = JSON.parse(ds[0].ds);
    return ds[0];
}



async function getServerNextData(id,sId){
    let ds = await mysql("SELECT *,DATE_FORMAT(`timestamp`,'%Y-%m-%d %H:%i:%S') AS `ts` FROM t_ms WHERE `id` = "+id);
    if(ds.length == 0 || ds[0].id == (id-1)) return {};

    ds[0].ds = JSON.parse(ds[0].ds)[sId];
    return ds[0];
}


async function getIdRange(st,et){
    let firstId =  await mysql("SELECT `id` FROM t_ms WHERE unix_timestamp(`timestamp`) >= '"+st+"' ORDER BY `id` ASC LIMIT 0,1; ");
    let lastId =  await mysql("SELECT `id` FROM t_ms WHERE unix_timestamp(`timestamp`) <='"+et+"' ORDER BY `id` DESC LIMIT 0,1;");

    if(firstId.length == 0 || lastId.length == 0) return [-1,-1];
    else return [firstId[0].id, lastId[0].id];
}


async function getTsRange(){
    let st =  await mysql("SELECT `timestamp` AS `ts` FROM t_ms ORDER BY `id` ASC LIMIT 0,1;");
    let et =  await mysql("SELECT `timestamp` AS `ts` FROM t_ms ORDER BY `id` DESC LIMIT 0,1;");

    return {'st':st[0].ts, 'et':et[0].ts};
}

async function getDsById(id,num){
    let ds = await mysql("SELECT *,DATE_FORMAT(`timestamp`,'%Y-%m-%d %H:%i:%S') AS `ts` FROM t_ms WHERE `id` >= "+id+" LIMIT 0,"+num);
    
    ds.forEach(d => {
        d.ds = JSON.parse(d.ds);
    });
    return ds;
}

async function getSsById(id,sId,num){
    let ds = await mysql("SELECT *,DATE_FORMAT(`timestamp`,'%Y-%m-%d %H:%i:%S') AS `ts` FROM t_ms WHERE `id` >= "+id+" LIMIT 0,"+num);
    
    ds.forEach(d=>{
        d.ds = JSON.parse(d.ds)[sId];
    })
    return ds;
}



module.exports = {
    getLatestIndex,getNextData,getServerNextData,getIdRange,getTsRange,getSsById,getDsById
}
